const path = require("path");
const webpack = require("webpack");
const merge = require('webpack-merge');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin'); //css独立打包
const CommonsChunkPlugin = webpack.optimize.CommonsChunkPlugin; //抽出公共JS
const CopyWebpackPlugin = require('copy-webpack-plugin'); //复制文件
const OpenBrowserPlugin = require('open-browser-webpack-plugin'); //自动打开浏览器
const precss = require('precss');
const autoprefixer = require('autoprefixer');//css3兼容性处理 自动加前缀
const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin'); //css压缩 
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');


const tempUrl = process.env.NODE_ENV == 'dev' ? '/' : './';
var statics = process.env.NODE_ENV == 'dev' ? 'static/' : './static/';
var baseConfig = {
  entry: {
    app: ['babel-polyfill', './src/main.js'],
    'vendor': ['vue', 'vuex', 'vue-router', 'axios', 'babel-polyfill']
  },
  output: {
    path: path.join(__dirname, "./dist"),
    filename: statics + 'js/[name].js',
    publicPath: tempUrl,
    chunkFilename: statics + "js/chunk/[name].[chunkHash:8].js"
  },
  resolve: {
    extensions: ['.js', '.vue', '.json'],
    alias: {
      'vue': 'vue/dist/vue.js',
      '@': path.join(__dirname, './src')
    }
  },
  module: {
    rules: [{
      test: /\.(js|vue)$/,
      loader: 'eslint-loader',
      enforce: 'pre',
      include: [path.join(__dirname, './src')],
      options: {
        formatter: require('eslint-friendly-formatter')
      }
    },
    { test: /\.vue$/, loader: 'vue-loader' }, 
    { test: /\.scss|\.css$/, use: ExtractTextPlugin.extract(
              { fallback: 'style-loader?minimize',publicPath: '../../', use: ['css-loader?minimize', 'sass-loader?minimize', 'postcss-loader?minimize'] }
    ) },
    { test: /\.jpe?g$|\.gif$|\.png$/, loader: 'url-loader?limit=8192&name=' + statics + 'image/[hash:8].[name].[ext]' },
    { test: /\.svg$|\.woff$|\.ttf$|\.eot$/, loader: 'url-loader?limit=8192&name=' + statics + 'font/[hash:8].[name].[ext]' },
    { test: /\.json$/, loader: 'json-loader' },
    {
      test: /\.js$/,
      exclude: /node_modules/, // 处理除了nodde_modules里的js文件
      loader: 'babel-loader'
    }
    ]
  },
  plugins: [
    new webpack.LoaderOptionsPlugin({
      options: {
        postcss: function () {
          return [precss, autoprefixer];
        }
      }
    }),
    //css
    new ExtractTextPlugin(statics + 'css/[name].css?[contenthash]'),
    new OptimizeCSSPlugin({
      cssProcessorOptions: {
        safe: true
      }
    }),
    new CommonsChunkPlugin({
      name: ['vendor', 'common'],
      minChunks: Infinity
    }),
    //生成html文件
    new HtmlWebpackPlugin({
      filename: 'index.html',
      template: 'index.html', //启动页面
      inject: true //要把script插入到标签里
    }),
    new CopyWebpackPlugin([{
      from: __dirname + '/static',
      to: './public'
    }])
  ]
}

var buildConfig = {
  env: 'prod'
};
const argv = require('yargs').argv;
if (argv._.length > 0 || process.env.NODE_ENV) {
  buildConfig.env = argv._[0] || process.env.NODE_ENV || buildConfig.env;
  var fs = require('fs');
  var filename = './src/buildConfig.json';
  fs.writeFileSync(filename, JSON.stringify(buildConfig));
} else {
  buildConfig.env = 'dev';
}
var webpackConfig = null;
if (buildConfig.env === 'dev') { //开发环境
  const port = '8088'; //默认启动端口号
  webpackConfig = merge(baseConfig, {
    devtool: '#cheap-module-eval-source-map',
    devServer: {
      hot: true,
      inline: true, //实时刷新
      host: "0.0.0.0",
      port: port,
      contentBase: './public',
      historyApiFallback: true,
      disableHostCheck: true,
      proxy: { //本地代理
        '/api/*': {
          target: 'http://118.190.39.157:8080',//测试
          secure: false
        }
      }
    },
    plugins: [
      new webpack.HotModuleReplacementPlugin(), //代码热替换
      new OpenBrowserPlugin({ //自动打开浏览器
        url: 'http://localhost:' + port
      })
    ]
  })
  module.exports = webpackConfig;
} else { //线上环境
  webpackConfig = merge(baseConfig, {
    devtool: '#source-map',
    plugins: [
      new UglifyJsPlugin({
        uglifyOptions: {
          compress: {
            warnings: false
          }
        },
        parallel: true
      })
    ]
  });
  //手动启动webpack
  var ora = require('ora')
  var spinner = ora('=====开始编译中...');
  spinner.start();
  webpack(webpackConfig, function (err, stats) {
    spinner.stop();
    if (err) throw err
    process.stdout.write(stats.toString({
      colors: true,
      modules: false,
      children: false,
      chunks: false,
      chunkModules: false
    }) + '\n\n')
  })
}